import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    phone: '',
    code: '',
    flag: true,
    btnText: '获取验证码',
    disableBtn: false,
    countdown: 60
  },
  fangdou() {
    setTimeout(() => {
      this.setData({
        flag: true
      })
    }, 2000);
    this.setData({
      flag: false
    })
  },
  async loginfn() {
    if (!this.data.flag) return
    this.fangdou()
    if (!(/^1[3-9]\d{9}$/.test(this.data.phone))) return Toast('请输入正确的手机号');
    if (!(/^\d{6}$/.test(this.data.code))) return Toast('请输入正确的验证码格式');
    let res = await wx.http.post('/login', {
      "mobile": this.data.phone,
      "code": this.data.code
    })
    Toast(res.message);
    wx.setStorageSync('token', res.data.token);
    wx.reLaunch({
      url: '/pages/home/home'
    })
    // if (res.code == 10000) {
    //   let res2 = await wx.http.post('/refreshToken', {
    //     "Authorization": res.data.refreshToken,
    //   }, {
    //     header: {
    //       "Authorization": res.data.token
    //     }
    //   })
    // }
  },
  phoneinput(event: any) {
    this.setData({
      phone: event.detail.value,
    });
  },
  codeinput(event: any) {
    this.setData({
      code: event.detail.value,
    });
  },
  // 手机号校验函数
  async validatePhone() {
    if (!(/^1[3-9]\d{9}$/.test(this.data.phone))) return Toast('请输入正确的手机号');
    if (this.data.disableBtn) return;
    this.setData({
      disableBtn: true
    });
    let interval = setInterval(() => {
      let countdown = this.data.countdown - 1;
      if (countdown <= 0) {
        clearInterval(interval);
        this.setData({
          btnText: '获取验证码',
          disableBtn: false,
          countdown: 60
        });
      } else {
        this.setData({
          btnText: countdown + '秒后重新获取',
          countdown: countdown
        });
      }
    }, 1000);
  const res = await wx.http.get('/code', {
      mobile: this.data.phone
    })
    Toast(res.data.code);
  },
});